//
//  HMTabBar.swift
//  WeiBo
//
//  Created by 李立达 on 15/12/5.
//  Copyright © 2015年 heima11. All rights reserved.
//

import UIKit

class HMTabBar: UITabBar {

    
    /// 点击撰写按钮的事件闭包
    var CommonClickColure : (()->())?
    
    //懒加载撰写按钮
    lazy var CommonButton : UIButton = {
    
        let button = UIButton()
        
        button.addTarget(self, action: "commonButtonClick", forControlEvents:UIControlEvents.TouchUpInside)
        
        let image = UIImage(named: "tabbar_compose_button_highlighted")
        button.setBackgroundImage(image, forState: UIControlState.Highlighted)
        
        let imageNomal = UIImage(named: "tabbar_compose_button")
        
        button.setBackgroundImage(imageNomal, forState: UIControlState.Normal)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.sizeToFit()
    
        return button
    }()
    
    
    //点击方法
    func commonButtonClick () {
        
        CommonClickColure!()
    }
    
    
    //重写了init方法
   override init(frame: CGRect) {
        super.init(frame: frame)
    
        backgroundImage = UIImage(named: "tabbar_background")
        setupUI()
    }

    //如果从xib和sb 加载 必须实现此方法
   required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
     setupUI()
   }
    
    
    //手动遍历tabbar 设置每个空间的按钮frame
   override func layoutSubviews() {
    super.layoutSubviews()
    
    
    //设置撰写按钮的center值 不能用父类的center
    CommonButton.center = CGPointMake( frame.width*0.5 , frame.height*0.5)
    
    let childWith = CGFloat(frame.width/5)
    
    
    var index = 0
    
    
    for childView in subviews
    {
        //判断类型是不是UItabBarButton
        if childView.isKindOfClass(NSClassFromString("UITabBarButton")!)
        {
            let x = CGFloat(index) * childWith
            
            childView.frame = CGRect(x: x, y: 0, width: childWith, height: frame.height)
            
            index++
            
            if(index==2)
            {
                index++
            }
        }
     }
    }
    
    //添加撰写按钮
    func setupUI () {
        addSubview(CommonButton)
    }
    
    
    
}


